class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums)
    {
        int n = nums.size();
        vector<int> f(n), g(n);
        f[0] = g[0] = nums[0];
        int x = nums[0], y = nums[0];
        for (int i = 1; i < n; i++)
        {
            f[i] = max(nums[i], nums[i] + f[i - 1]);
            x = max(x, f[i]);
            g[i] = min(nums[i], nums[i] + g[i - 1]);
            y = min(y, g[i]);
        }
        int sum = 0;
        for (int i = 0; i < n; i++) sum += nums[i];

        return sum == y ? x : max(x, sum - y);
    }
};
class Solution {
public:
    int maxSubArray(vector<int>& nums)
    {
        int n = nums.size();
        int ret = nums[0];
        vector<int> dp(n);
        dp[0] = nums[0];
        for (int i = 1; i < n; i++)
        {
            dp[i] = max(nums[i], nums[i] + dp[i - 1]);
            ret = max(ret, dp[i]);
        }
        return ret;
    }
};
class Solution {
public:
    int maxProfit(int k, vector<int>& prices)
    {
        const int INF = 0x3f3f3f3f;
        int m = prices.size();
        vector<vector<int>> f(m, vector<int>(k + 1, -INF));
        auto g = f;
        f[0][0] = -prices[0];
        g[0][0] = 0;

        for (int i = 1; i < m; i++)
        {
            for (int j = 0; j <= k; j++)
            {
                f[i][j] = max(f[i - 1][j], g[i - 1][j] - prices[i]);
                g[i][j] = g[i - 1][j];
                if (j - 1 >= 0) g[i][j] = max(g[i][j], f[i - 1][j - 1] + prices[i]);
            }
        }

        int ret = 0;
        for (int j = 0; j <= k; j++)
            ret = max(ret, g[m - 1][j]);
        return ret;
    }
};